﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agro.Models;
using SN.Data;
using System.Data;
using Agro.Library;
namespace Agro.Services
{
    public class NoticeService : BaseService, INoticeService
    {

        public DataTable GetNoticeList(SN.Core.QueryBase query, WhereClip wclip)
        {
            Field[] fields = {T_Notice._.Notice_Title,T_Notice._.Notice_AttachmentName,T_Notice._.Notice_CreateDate,T_Notice._.Notice_ID,T_Notice._.Notice_CreateUser};

            DataTable dt = DB.From<T_Notice>()
                //.LeftJoin<T_User>(T_User._.User_ID == T_Notice._.Notice_CreateUser)
               .Select(fields).Where(wclip).ToTablePage(query);
            return dt;
        }
        public List<T_Notice> GetTopNoticeList(int topsize)
        {
            List<T_Notice> dt = (List<T_Notice>)DB.From<T_Notice>().OrderBy(T_Notice._.Notice_CreateDate.Desc).GetTop(topsize).ToList();
            return dt;
        }
        public bool SaveNotice(T_Notice Notice, out string Msg, CurrentUser User)
        {
            Msg = string.Empty;
            using (DbTrans trans = DB.BeginTrans())
            {
                try
                {
                    if (Notice.Notice_ID > 0)
                    {
                        Notice.Attach(); //更新
                    }
                    else
                    {
                        //新增
                        Notice.Notice_CreateUser = User.UserInfo.User_ID.ToString();
                        Notice.Notice_CreateDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
                        Notice.Detach();
                    }
                    trans.Save<T_Notice>(Notice);
                    //提交
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Msg = ex.Message;
                    return false;
                }
            }
            return true;
        }

        public bool DeleteNotice(string ids, out string Msg)
        {
            Msg = string.Empty;
            int iCount = 0;
            try
            {
                iCount = DB.Delete<T_Notice>(T_Notice._.Notice_ID.In(ids.Split(',')));
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
            }
            return iCount > 0 ? true : false;
        }

        public T_Notice GetNoticeDetail(string id)
        {
            return DB.From<T_Notice>().Where(T_Notice._.Notice_ID == id).ToSingle();
        }
    }
}
